import { ArgumentsHost, Catch, HttpException, WsExceptionFilter } from "@nestjs/common";
import { WsException } from "@nestjs/websockets";
import { MyWsErrorResponse } from "src/common/model";
import { WsCommonException } from "src/exception";
import { WsEvent } from "src/socket/ws.event.enum";

@Catch(WsException, HttpException, Error)
export class MyWsExceptionFilter implements WsExceptionFilter<WsException | HttpException> {
    catch(exception, host: ArgumentsHost) {
        const client = host.switchToWs().getClient();

        const eventName = host.switchToWs().getPattern();

        const response = new MyWsErrorResponse(999, eventName, `${exception.message || exception}`);

        if (exception instanceof HttpException) {
            let obj: any = exception.getResponse();
            obj = obj.message instanceof Array ? obj.message[0] || obj.error : obj.message || obj.error;
            response.code = exception.getStatus();
            response.message = obj || response.message;
        } else if (exception instanceof WsCommonException) {
            response.code = exception.code;
        }

        client.emit(WsEvent.EXCEPTION, response.toJson());
    }
}
